package com.netx.generics.io;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.net.InetAddress;

import com.netx.generics.basic.Checker;
import com.netx.generics.basic.IllegalUsageException;

//TODO put FilenameFilters working
//TODO guarantee that IOExceptions are not re-processed, otherwise they'll be translated to UnknownIOException
// (maybe dispatch to the ProtocolProvider, instead of throwing UnknowinIOException?)
public class FileSystem extends DirectoryImpl {
	
	private FilenameFilter _filter;

	public FileSystem(Location loc) throws IOException {
		super(null, ProtocolImpl.getProvider((Location)Checker.checkNull(loc, "loc"), ""));
		_filter = null;
		// This throws UnknownHostException if the host is unreachable: 
		InetAddress.getByName(loc.getHost());
		try {
			if(!provider.exists()) {
				// Paths like \\some-machine\\ (server root) return false on "exists".
				// Therefore, if this is the case, no exception should be thrown.
				// The above code (InetAddress.getByName) makes sure that the host is reachable.
				if(provider.base.getPhysicalPath().startsWith("//") && provider.base.getPath().equals("/")) {
					// noop;
				}
				else {
					throw new FileNotFoundException(provider.base.getPhysicalPath());
				}
			}
			else if(!provider.isDirectory()) {
				throw new IllegalUsageException("'"+provider.base.getPhysicalPath()+"': not a directory");
			}
		}
		catch(IOException io) {
			throw provider.translate(io, "/");
		}
		catch(RuntimeException re) {
			throw provider.translate(re, "/");
		}
	}
	
	public Location getLocation() {
		return provider.base;
	}
	
	public void setFilenameFilter(FilenameFilter filter) {
		_filter = filter;
	}
	
	public FilenameFilter getFilenameFilter() {
		return _filter;
	}

	// OVERRIDEN METHODS:
	public FileSystem getFileSystem() {
		return this;
	}
	
	public Directory getParent() {
		return null;
	}
	
	public boolean delete() {
		throw new IllegalUsageException("cannot delete a FileSystem");
	}

	public void deleteOnExit() {
		throw new IllegalUsageException("cannot delete a FileSystem");
	}
	
	public void renameTo(String name) throws IOException {
		throw new IllegalUsageException("cannot rename a FileSystem");
	}
}
